package org.turbobytes.unikey.util;

import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;

import java.util.Properties;
import java.io.InputStream;
import java.io.IOException;

/**
 * Utility methods related to File, Properties, Resource Bundle and IO
 *
 * @author Ganeshji Marwaha
 * @since Aug 5, 2010
 */
public class FileUtil {
  private static final Log log = LogFactory.getLog(FileUtil.class);

  /**
   * Load a properties file from classpath given the {@param fileName}.
   * If it is not found, it returns an empty properties instance.
   * 
   * @param fileName to load from classpath
   * @return loaded properties instance
   */
  public static Properties loadPropertiesFromClasspath(String fileName) {
    Properties properties = new Properties();
    InputStream inputStream = FileUtil.class.getClassLoader().getResourceAsStream(fileName);

    try {
      if (inputStream != null) properties.load(inputStream);
    } catch(IOException e) {
      log.warn("There was an exception reading from InputStream. Returning blank properties instance instead.");
    }

    return properties;
  }
  
  /**
   * Load any file from classpath given the {@param fileName}.
   * 
   * @param fileName to load from classpath
   * @return inputStream
   */
  public static InputStream getFileStreamFromClasspath(String fileName) {
    InputStream inputStream = FileUtil.class.getClassLoader().getResourceAsStream(fileName);

    return inputStream;
  }

  /**
   * Merges mergeFrom to mergeTo so that the mergeTo will contain the resulting merged properties.
   * This was the default properties can be in the {@code mergeTo} and the user specified properties can be in
   * {@code mergeFrom} and only the properties that were specified by the user gets merged into the default and the
   * remaining default properties still exist.
   * 
   * @param mergeTo - properties will be merged into this. Like default configuration
   * @param mergeFrom - properties that will override {@code mergeTo} values
   * @return merged mergeTo instance
   */
  public static Properties mergeProperties(Properties mergeTo, Properties mergeFrom) {
    if(mergeTo == null && mergeFrom == null) return new Properties();
    if(mergeTo == null) return mergeFrom;
    if(mergeFrom == null) return mergeTo;

    for(Object objKey: mergeFrom.keySet()) {
      String key = (String) objKey;
      mergeTo.setProperty(key, mergeFrom.getProperty(key));
    }

    return mergeTo;
  }
}
